package com.xxgc.qinglian.qinglianserver.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.qinglian.qinglianserver.entity.*;
import com.xxgc.qinglian.qinglianserver.result.Result;
import com.xxgc.qinglian.qinglianserver.service.WebSocketService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("project")
@Tag(name = "项目查询接口")
public class ProjectController {
    @Autowired
    private ProjectEntityRepository projectEntityRepository;
    @Autowired
    private UserEntityRepository userEntityRepository;
    @Autowired
    private VoteRecordEntityRepository voteRecordEntityRepository;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private UserVoteEntityRepository userVoteEntityRepository;
    @Autowired
    private VoteEntityRepository voteEntityRepository;
    // 查询所有项目
    @PostMapping("getAllProject")
    public Result getAllProject() {
        List<ProjectEntity> allProjects = projectEntityRepository.list(new QueryWrapper<>());
        return Result.success(allProjects).msg("所有项目数据");
    }
    @PostMapping("getVoteId")
    public Result getVoteId() {
        QueryWrapper qw=new QueryWrapper<>();
        qw.eq("vote_status", "进行中");
        VoteEntity VoteEntity = voteEntityRepository.getOne(qw);
        System.out.println(VoteEntity.getVoteId());
        return Result.success(VoteEntity.getVoteId()).msg("获取投票ID成功");
    }

    @PostMapping("setRemainingVotes")
    public Result setRemainingVotes() {
        Integer userId = StpUtil.getLoginIdAsInt();
        QueryWrapper qw1 = new QueryWrapper<>();
        qw1.eq("user_id", userId);
        UserVoteEntity userVoteEntity = userVoteEntityRepository.getOne(qw1);
        System.out.println("userVoteEntity = " + userVoteEntity);
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("vote_status", "进行中");
        UserEntity userEntity = userEntityRepository.getById(userId);
        System.out.println("dfkdhfkjfo");

        VoteEntity one = voteEntityRepository.getOne(qw);
        if (userVoteEntity == null) {


            System.out.println("qw = " + qw);
            System.out.println("one = " + one);

            UserVoteEntity userVoteEntity1 = new UserVoteEntity();
            userVoteEntity1.setUserId(userId.toString());
            userVoteEntity1.setVoteId(one.getVoteId());
            if (userEntity.getUserType() == 1) {
                userVoteEntity1.setRemainingVotes(one.getUserVote2());
            } else if (userEntity.getUserType() == 0) {
                userVoteEntity1.setRemainingVotes(one.getUserVote1());
            }
            userVoteEntityRepository.save(userVoteEntity1);
            return Result.success(userVoteEntity1.getRemainingVotes()).msg("获取剩余票数成功");
        }
//        QueryWrapper<UserVoteEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        UserVoteEntity userVoteEntity2 = userVoteEntityRepository.getOne(queryWrapper);
        if (userVoteEntity != null && one.getVoteId().equals(userVoteEntity.getVoteId())) {
            System.out.println("走这里1");
            return Result.success(userVoteEntity.getRemainingVotes()).msg("获取剩余票数成功");
        } else {
            System.out.println("走这里2");

            QueryWrapper<UserVoteEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

             userVoteEntity = userVoteEntityRepository.getOne(queryWrapper);

            if (userVoteEntity != null) {
                // 用户已存在，更新剩余票数和 voteId
                if (userEntity.getUserType() == 1) {
                    userVoteEntity.setRemainingVotes(one.getUserVote2());
                } else if (userEntity.getUserType() == 0) {
                    userVoteEntity.setRemainingVotes(one.getUserVote1());
                }

                // 更新 voteId（假设你有新的 voteId 需要设置）
                userVoteEntity.setVoteId(one.getVoteId()); // 替换为实际的 voteId

                // 执行更新操作
                userVoteEntityRepository.updateById(userVoteEntity);



            return Result.success(userVoteEntity.getRemainingVotes()).msg("获取剩余票数成功");
        }else {
                return Result.fail("获取剩余票数失败");
            }
            }
    }


    @PostMapping("getRemainingVotes")
    public Result getRemainingVotes() {
        Integer userId = StpUtil.getLoginIdAsInt();
        QueryWrapper qw1=new QueryWrapper<>();
        qw1.eq("user_id",userId);
        UserVoteEntity one = userVoteEntityRepository.getOne(qw1);
        if(one!=null){
            return Result.success(one.getRemainingVotes()).msg("获取剩余票数成功");
        }

            return  Result.fail("获取剩余票数失败");





    }

    // 投票
    @PostMapping("/vote")
    @Transactional
    public Result vote(@RequestBody Map<String, Object> params) {
        Object projectIdObj = params.get("projectId");
        if (projectIdObj == null) {
            return Result.fail("缺少 projectId 参数");
        }
        int projectId = Integer.parseInt(projectIdObj.toString());
        Integer userId = StpUtil.getLoginIdAsInt();
        UserEntity user = userEntityRepository.getById(userId);
        ProjectEntity project = projectEntityRepository.getById(projectId);
        if (user == null || project == null) {
            return Result.fail("用户或项目不存在");
        }

        // 根据用户类型增加对应票数
        if (user.getUserType() == 1) {
            project.setTotalInsideVotes(project.getTotalInsideVotes() + 1);
        } else if (user.getUserType() == 0) {
            project.setTotalVotes(project.getTotalVotes() + 1);
        } else {
            return Result.fail("未知用户类型");
        }

        // 更新项目票数
        boolean updated = projectEntityRepository.updateById(project);
        if (!updated) {
            throw new RuntimeException("更新票数失败");
        }

        // 插入投票记录
        VoteRecordEntity voteRecord = new VoteRecordEntity();
        voteRecord.setUserId(userId);
        voteRecord.setProjectId(projectId);
        voteRecord.setVotes(1);
        voteRecord.setVoteTime(LocalDateTime.now());
        boolean saved = voteRecordEntityRepository.save(voteRecord);
        if (!saved) {
            throw new RuntimeException("保存投票记录失败");
        }

        // 更新用户剩余票数
        QueryWrapper<UserVoteEntity> voteQueryWrapper = new QueryWrapper<>();
        voteQueryWrapper.eq("user_id", userId);
        UserVoteEntity userVoteEntity = userVoteEntityRepository.getOne(voteQueryWrapper);
        System.out.println("userVoteEntity1213 = " + userVoteEntity);
        if (userVoteEntity != null && userVoteEntity.getRemainingVotes() > 0) {
            userVoteEntity.setRemainingVotes(userVoteEntity.getRemainingVotes() - 1);
            System.out.println("userVoteEntity23433 = " + userVoteEntity);
            userVoteEntityRepository.updateById(userVoteEntity);

            // 点对点发送剩余票数更新
            webSocketService.sendRemainingVotesToUser(userId, userVoteEntity.getRemainingVotes());
        } else {
            throw new RuntimeException("票数已用尽，无法投票");
        }

        // 广播项目票数更新
        webSocketService.broadcastProjectVotesUpdate();

        return Result.success("投票成功");
    }

    // 取消投票
    @PostMapping("/cancelVote")
    @Transactional
    public Result cancelVote(@RequestBody Map<String, Object> params) {
        Object projectIdObj = params.get("projectId");
        if (projectIdObj == null) {
            return Result.fail("缺少 projectId 参数");
        }
        int projectId = Integer.parseInt(projectIdObj.toString());
        Integer userId = StpUtil.getLoginIdAsInt();
        ProjectEntity project = projectEntityRepository.getById(projectId);
        if (project == null) {
            return Result.fail("项目不存在");
        }

        // 根据用户类型减少对应票数
        UserEntity user = userEntityRepository.getById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        if (user.getUserType() == 1) {
            project.setTotalInsideVotes(Math.max(0, project.getTotalInsideVotes() - 1));
        } else if (user.getUserType() == 0) {
            project.setTotalVotes(Math.max(0, project.getTotalVotes() - 1));
        } else {
            return Result.fail("未知用户类型");
        }

        // 更新项目票数
        boolean updated = projectEntityRepository.updateById(project);
        if (!updated) {
            throw new RuntimeException("更新票数失败");
        }

        // 删除投票记录
        boolean deletedCount = voteRecordEntityRepository.remove(
                new QueryWrapper<VoteRecordEntity>()
                        .eq("user_id", userId)
                        .eq("project_id", projectId)
        );

        // 更新用户剩余票数
        QueryWrapper<UserVoteEntity> voteQueryWrapper = new QueryWrapper<>();
        voteQueryWrapper.eq("user_id", userId);
        UserVoteEntity userVoteEntity = userVoteEntityRepository.getOne(voteQueryWrapper);
        if (userVoteEntity != null) {
            userVoteEntity.setRemainingVotes(userVoteEntity.getRemainingVotes() + 1);
            userVoteEntityRepository.updateById(userVoteEntity);

            // 点对点发送剩余票数更新
            webSocketService.sendRemainingVotesToUser(userId, userVoteEntity.getRemainingVotes());
        } else {
            userVoteEntity = new UserVoteEntity();
            userVoteEntity.setUserId(userId.toString());
            userVoteEntity.setRemainingVotes(1);
            userVoteEntityRepository.save(userVoteEntity);
        }

        // 广播项目票数更新
        webSocketService.broadcastProjectVotesUpdate();

        return Result.success("取消投票成功");
    }

    // 插入项目
    @PostMapping("insertProject")
    public Result insertProject(@RequestBody ProjectEntity projectEntity) {
        boolean success = projectEntityRepository.save(projectEntity);
        if (success) {
            // 项目添加成功后广播更新
            Integer userId = StpUtil.getLoginIdAsInt();
            webSocketService.broadcastProjectVotesUpdate();
            return Result.success();
        } else {
            return Result.fail("保存项目失败");
        }
    }
}
